const Koa = require('koa')
const Router = require('koa-router')
const static = require('koa-static')
const bodyParser = require('koa-bodyparser')
const app = new Koa()

const conf = require('./conf')
app.use(bodyParser)
const router = new Router()

app.use(static(__dirname + '/'))

const wechat = require('co-wechat')


// 验证
router.get('/wechat', ctx=>{
  console.log('微信认证...', ctx.url)
  const {query} = url.parse(ctx.url, true)
  const {
    signature, // 微信加密签名
    timestamp, // 时间戳
    nonce, // 随机数
    echostr // 随机字符串
  } = query

  console.log('wechat', query)

  // 排序连接
  let str = [conf.token, timestamp, nonce].sort().join('')
  console.log('str', str)
  let strSha1 = crypto.createHash('sha1').update(str).digest('hex')
  
  if(signature == strSha1){
    // 返回的始终是微信返回给我们的一个值，我们判读是否正常，
    ctx.body = echostr
  } else {
    ctx.body = '不是微信'
  }
})


app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)


